package com.rockcent.wechat.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.BigDecimalUtils;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.mall.lib.helper.QRCodeHelper;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.wechat.Routes;
import com.rockcent.wechat.helper.CustomerHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by DK on 16/10/21.
 */
@RestController
@RequestMapping(value = Routes.API_PREFIX)
public class GiftPacketController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(GiftPacketController.class);
    @Autowired
    private QRCodeHelper qrCodeHelper;
    @Autowired
    private CustomerHelper customerHelper;

    @Autowired
    private MerchantGiftPacketRepository merchantGiftPacketRepository;
    @Autowired
    private MerchantGiftPacketProductRepository merchantGiftPacketProductRepository;
    @Autowired
    private MerchantProductRepository merchantProductRepository;
    @Autowired
    private MallFinancialSettingsRepository mallFinancialSettingsRepository;
    @Autowired
    private MallOrderRepository mallOrderRepository;
    @Autowired
    private CustomerGiftWalletRepository customerGiftWalletRepository;
    @Autowired
    private MallRepository mallRepository;

    @Autowired
    private CustomerCouponWalletRepository customerCouponWalletRepository;


    /**
     * @api {get} /api/v2/mall/gift/packet/page 平台产品礼包 分页
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiSuccess {Long} id 礼包ID
     * @apiSuccess {String} name 礼包名称
     * @apiSuccess {String} coverUrl 广告封面
     * @apiSuccess {String} intro 礼包介绍
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {BigDecimal} basePrice 总价
     * @apiSuccess {BigDecimal} sellPrice 礼包价
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {Long} mallId 商城ID
     * @apiSuccess {String=S2_SELLING("已上架"),S6_UNSTART("未开始")} status 礼包状态
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code" : "1".
     *     "desc" : "成功",
     *     "data" : [
     *            {
     *                "id" : 23,
     *                "name" : "组合礼包",
     *                "coverUrl" : "/20160601/201606011413084VOvLKgN.jpg",
     *                "intro" : "礼包介绍",
     *                "shareFee" : 21,
     *                "basePrice" : 231,
     *                "sellPrice" : 222,
     *                "merchantId" : 2,
     *                "mallId" : 1,
     *                "status" : "S2_SELLING",
     *            },
     *            .......
     *     ]
     * }
     */
    @RequestMapping(value = Routes.MALL_GIFT_PACKET_PAGE, method = RequestMethod.GET)
    public JsonResult mallGiftPacketPage(HttpServletRequest request, GiftPacketDto giftPacketDto){
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            PageResult<GiftPacketDto> pageResult = merchantGiftPacketRepository.findMallGiftPacketPage(customerDto.getMallId(), this.getPage(giftPacketDto.getPageNo(), giftPacketDto.getPageSize()));
            jr.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/merchant/gift/packet/page 商家产品礼包 分页
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam  {Long} merchantId <code>必须参数</code> 商家ID
     * @apiParam {Long} [productId] 产品ID,如果产品ID不为空，查以该产品为组成的礼包
     *
     * @apiSuccess {Long} id 礼包ID
     * @apiSuccess {String} name 礼包名称
     * @apiSuccess {String} coverUrl 广告封面
     * @apiSuccess {String} intro 礼包介绍
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {BigDecimal} basePrice 总价
     * @apiSuccess {BigDecimal} sellPrice 礼包价
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {Long} mallId 商城ID
     * @apiSuccess {String=S2_SELLING("已上架"),S6_UNSTART("未开始")} status 礼包状态
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code" : "1".
     *     "desc" : "成功",
     *     "data" : [
     *            {
     *                "id" : 23,
     *                "name" : "组合礼包",
     *                "coverUrl" : "/20160601/201606011413084VOvLKgN.jpg",
     *                "intro" : "礼包介绍",
     *                "shareFee" : 21,
     *                "basePrice" : 231,
     *                "sellPrice" : 222,
     *                "merchantId" : 2,
     *                "mallId" : 1,
     *                "status" : "S2_SELLING",
     *            },
     *            .......
     *     ]
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_PAGE, method = RequestMethod.GET)
    public JsonResult merchantGiftPacketPage(HttpServletRequest request, GiftPacketDto giftPacketDto,Long productId){
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            if (giftPacketDto.getMerchantId() == null) {
                jr.remind("商家ID 不能为空",log);
                return;
            }
            //如果产品ID不为空，查以该产品为组成的礼包
            List<Long> packetIds = null;
            if (productId != null){
                List<MerchantGiftPacketProduct> merchantGiftPacketProductPage = merchantGiftPacketProductRepository.findByProductId(productId);
                packetIds = merchantGiftPacketProductPage.stream().map(MerchantGiftPacketProduct::getPacketId).collect(Collectors.toList());
            }
            PageResult<GiftPacketDto> pageResult = merchantGiftPacketRepository.merchantGiftPacketPage(customerDto.getMallId(), giftPacketDto.getMerchantId(),packetIds, this.getPage(giftPacketDto.getPageNo(), giftPacketDto.getPageSize()));
            jr.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/gift/packet/info 产品礼包 详情
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} couponId <code>必须参数</code> 礼包ID
     *
     * @apiSuccess {Long} id 礼包ID
     * @apiSuccess {String} name 礼包名称
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Date} dateEnabled 礼包开始时间
     * @apiSuccess {Date} dateDisabled 礼包结束时间
     * @apiSuccess {String} marketPacketId 分销礼包唯一的识别码
     * @apiSuccess {String} coverUrl 广告封面
     * @apiSuccess {String} intro 礼包介绍
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {BigDecimal} basePrice 总价
     * @apiSuccess {BigDecimal} sellPrice 礼包价
     * @apiSuccess {BigDecimal} friendPrice 朋友价
     * @apiSuccess {Boolean} isRecommend 是否共享营销
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {Long} mallId 商城ID
     * @apiSuccess {String=S1_DRAFTED("草稿"), S2_SELLING("已上架"), S3_UNLOAD("已下架"), S4_SOLDOUT("已售完"), S5_FINISHED("已结束"), S6_UNSTART("未开始")} status 礼包状态
     *
     * @apiSuccess {Long} masterPacketProduct_productId 主产品
     * @apiSuccess {String} masterPacketProduct_name 主产品名称
     * @apiSuccess {String} masterPacketProduct_merchantName 主产品商家名称
     * @apiSuccess {BigDecimal} masterPacketProduct_sellPrice 主产品售价
     * @apiSuccess {Long} masterPacketProduct_quantity 主产品库存
     * @apiSuccess {BigDecimal} masterPacketProduct_resellFee 主产品佣金
     *
     * @apiSuccess {Long} collocationPacketProductList_productId 搭配产品
     * @apiSuccess {String} collocationPacketProductList_name 搭配产品名称
     * @apiSuccess {String} collocationPacketProductList_merchantName 搭配产品商家名称
     * @apiSuccess {BigDecimal} collocationPacketProductList_sellPrice 搭配产品售价
     * @apiSuccess {Long} collocationPacketProductList_quantity 搭配产品库存
     * @apiSuccess {BigDecimal} collocationPacketProductList_resellFee 搭配产品佣金
     *
     * @apiSuccess {Long} merchantPacketCouponList_couponId 卡卷id
     * @apiSuccess {String} merchantPacketCouponList_name 卡卷
     * @apiSuccess {String=ALL_STORE("所有门店"), ALL_PRODUCT("所有产品"), PART_STORE("指定门店"), PART_PRODUCT("PART_PRODUCT")} merchantPacketCouponList_useScope 卡卷适用范围
     * @apiSuccess {String=VOUCHERS("抵用券"), DISCOUNT("折扣券")} merchantPacketCouponList_type 卡卷
     * @apiSuccess {String} merchantPacketCouponList_merchantName 卡卷商家名称
     * @apiSuccess {Long} merchantPacketCouponList_leaveTotal 卡卷库存
     * @apiSuccess {String} merchantPacketCouponList_introduction 卡卷简介
     *
     * @apiSuccessExample {json} Response
     * {
     *     "code" : "1".
     *     "desc" : "成功",
     *     "data" : [
     *            {
     *               "id" : 23,
     *                "name" : "组合礼包",
     *                "dateCreated" : "2016-07-22 10:49:28",
     *                "lastUpdated" : "2016-07-22 10:49:28",
     *                "dateEnabled" : "2016-07-22 10:49:28",
     *                "dateDisabled" : "2016-07-22 10:49:28",
     *                "marketPacketId" : 343,
     *                "coverUrl" : "/20160601/201606011413084VOvLKgN.jpg",
     *                "intro" : "礼包介绍",
     *                "shareFee" : 21,
     *                "basePrice" : 231,
     *                "sellPrice" : 222,
     *                "isRecommend" : true,
     *                "merchantId" : 2,
     *                "mallId" : 1,
     *                "status" : "S2_SELLING"
     *                "masterPacketProduct" : [
     *                      "productId" : 23,
     *                      "name" : "牛奶",
     *                      "merchantName" : "大口九",
     *                      "sellPrice" : 234,
     *                      "quantity" : 333,
     *                      "resellFee" : 23
     *                ],
     *                "collocationPacketProductList" : [
     *                      {
     *                          "productId" : 23,
     *                          "name" : "牛奶",
     *                          "merchantName" : "大口九",
     *                          "sellPrice" : 234,
     *                          "quantity" : 222,
     *                          "resellFee" : 4
     *                      },
     *                      ......
     *                ],
     *                "merchantPacketCouponList" : [
     *                  {
     *                  "couponId": 20,
     *                  "name": "傻了么",
     *                  "useScope": "ALL_STORE",
     *                  "type": "VOUCHERS",
     *                  "merchantName": "b1测试商户 X",
     *                  "leaveTotal": 6,
     *                  "introduction": "满享7折"
     *                  },
     *                     ......
     *                ]
     *            }
     *     ]
     * }
     *
     */
    @RequestMapping(value = Routes.GIFT_PACKET_INFO, method = RequestMethod.GET)
    public JsonResult giftPacketInfo(HttpServletRequest request, @PathVariable Long couponId){
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            if (couponId == null) {
                jr.remind("couponId:" + Mall.CHECK_ID_IS_NOT_NULL,log);
                return;
            }
            MerchantGiftPacket giftPacket = merchantGiftPacketRepository.findOne(couponId);
            GiftPacketDto giftPacketDto = new GiftPacketDto();
            RBeanUtils.copyProperties(giftPacket, giftPacketDto);
            //类型不同的
            giftPacketDto.setBasePrice(giftPacket.getBasePrice().doubleValue());
            giftPacketDto.setSellPrice(giftPacket.getSellPrice().doubleValue());
            giftPacketDto.setShareFee(giftPacket.getShareFee().doubleValue());
            giftPacketDto.setStatus(giftPacket.getStatus().toString());
            MallFinancialSettings mallFinancialSettings = mallFinancialSettingsRepository.findTop1ByMallIdAndIsDeleteOrderByLastUpdatedDesc(customerDto.getMallId(), Whether.NO);
            BigDecimal shareRate = mallFinancialSettings.getShareFeeRate() == null ? BigDecimal.valueOf(0): mallFinancialSettings.getShareFeeRate();
            BigDecimal shareFeeRates = BigDecimalUtils.divide(BigDecimal.valueOf(100-shareRate.doubleValue()), "100");
            giftPacketDto.setFriendPrice(giftPacket.getSellPrice().subtract(giftPacket.getShareFee().multiply(shareFeeRates)).doubleValue());
            List<MerchantGiftPacketProductDto> masterProduct = merchantGiftPacketRepository.findGiftPacketProduct(giftPacket.getId(), GiftPacketProductType.MASTER);
            if (masterProduct.size() > 0) {
                giftPacketDto.setMasterPacketProduct(masterProduct.get(0));
            }
            List<MerchantGiftPacketProductDto> collocationProduct = merchantGiftPacketRepository.findGiftPacketProduct(giftPacket.getId(), GiftPacketProductType.COLLOCATION);
            giftPacketDto.setCollocationPacketProductList(collocationProduct);
            List<MerchantGiftPacketCouponDto> merchantCoupon = merchantGiftPacketRepository.findMerchantCouponList(giftPacket.getId());
            giftPacketDto.setMerchantPacketCouponList(merchantCoupon);
            jr.data = giftPacketDto;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/gift/packet/by_product 查询包含某商品的礼包
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} productId 产品ID
     * @apiParam {Integer} pageNo 页
     * @apiParam {Integer} pageSize 页记录数
     *
     * @apiSuccess {Long} id 礼包ID
     * @apiSuccess {String} name 礼包名称
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Date} dateEnabled 礼包开始时间
     * @apiSuccess {Date} dateDisabled 礼包结束时间
     * @apiSuccess {String} marketPacketId 分销礼包唯一的识别码
     * @apiSuccess {String} coverUrl 广告封面
     * @apiSuccess {String} intro 礼包介绍
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {BigDecimal} basePrice 总价
     * @apiSuccess {BigDecimal} sellPrice 礼包价
     * @apiSuccess {Boolean} isRecommend 是否共享营销
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {Long} mallId 商城ID
     * @apiSuccess {BigDecimal} resellFee 分销佣金
     * @apiSuccess {String=S1_DRAFTED("草稿"), S2_SELLING("已上架"), S3_UNLOAD("已下架"), S4_SOLDOUT("已售完"), S5_FINISHED("已结束"), S6_UNSTART("未开始")} status 礼包状态
     *
     * @apiSuccess {List} productList 产品列表
     *
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} name 名称
     * @apiSuccess {BigDecimal} basePrice 原价
     * @apiSuccess {BigDecimal} sellPrice 售价
     * @apiSuccess {Long} quantity  库存数量
     * @apiSuccess {Boolean} refundable 是否支持过期退
     * @apiSuccess {Boolean} sellnow 是否立即开售
     * @apiSuccess {Date} dateSelling 开售时间
     * @apiSuccess {Long} limitCount 限购数量
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {String} logoUrls 多LOGO图
     * @apiSuccess {String} note 卖点介绍
     * @apiSuccess {String} status 状态 SELLING("在售"), SUPPLIER_CANCEL_SOLDOUT("分销市场 供应商取消供货 已下架"),DISTRIBUTOR_CANCEL_SOLDOUT("分销市场 分销商取消代销 已下架"), SOLDOUT("已下架"), EXPIRED("已过期"), DELETED("已删除"), WAIT_APPLY("待申请"), WAIT_AUDIT("待审核"), AUDIT_PASS("审核通过"), AUDIT_FAIL("审核不通过")
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} serveRate 服务费比率
     * @apiSuccess {String} shippingType 支持的物流类型 SHOP_PICKUP("到店自取"), SHIPPING("物流"), SHOP_PICKUP_AND_SHIPPING("物流及到店自取")
     * @apiSuccess {BigDecimal} resellFee 分销佣金
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {Boolean} recommend 是否在分销市场展示
     * @apiSuccess {Integer} totalCount 总记录数
     * @apiSuccess {Integer} totalPage 总页数
     * @apiSuccess {Integer} pageNo 页码
     * @apiSuccess {Integer} pageSize 每页记录数
     *
     * @apiSuccessExample {json} Response
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *          "data": [
     *                      {
     *                          "id": 157,
     *                          "dateCreated": "2016-10-20 19:17:52",
     *                          "lastUpdated": "2016-10-20 19:17:52",
     *                          "name": "多点",
     *                          "coverUrl": "http://uploads.rockcent.com//uat/product/face/201610/201917268260820f33f-8fa0-4562-bff7-83b05d0a6bb4apic15377_s.jpg",
     *                          "dateEnabled": "2016-10-20 07:15:32",
     *                          "dateDisabled": "2016-10-31 07:15:35",
     *                          "intro": "<p>地方</p>",
     *                          "shareFee": 2,
     *                          "basePrice": 0,
     *                          "sellPrice": 0,
     *                          "status": "S2_SELLING",
     *                          "merchantId": 96,
     *                          "mallId": 15,
     *                          "merchantName": "chenqiutian",
     *                          "resellFee": 6.1,
     *                          "productList": [
     *                                              {
     *                                              "id": 647,
     *                                              "dateCreated": "2016-10-17 15:11:01",
     *                                              "lastUpdated": "2016-10-17 15:20:51",
     *                                              "version": 2,
     *                                              "name": "我修改名称，看看分销商那边改了没",
     *                                              "type": "GOODS",
     *                                              "basePrice": 12,
     *                                              "sellPrice": 10,
     *                                              "quantity": 1000,
     *                                              "carriage": 0,
     *                                              "refundable": false,
     *                                              "barcode": "",
     *                                              "sellnow": true,
     *                                              "dateSelling": "2016-10-17 15:11:00",
     *                                              "limitCount": 0,
     *                                              "logoUrl": "http://uploads.rockcent.com//uat/product/face/201610/17158522593c9f5c32-938c-4b55-a55e-25259b2aa596u=1468730664,161278931&fm=21&gp=0.jpg",
     *                                              "logoUrls": "[\"http://uploads.rockcent.com//uat/product/face/201610/17158522593c9f5c32-938c-4b55-a55e-25259b2aa596u=1468730664,161278931&fm=21&gp=0.jpg\"]",
     *                                              "note": "可爱两边，但是我怎么不觉得可爱呢",
     *                                              "status": "SELLING",
     *                                              "mallId": 15,
     *                                              "merchantId": 96,
     *                                              "merchantName": "chenqiutian@rockcent.com_15是",
     *                                              "serveRate": "2.5",
     *                                              "shippingType": "SHIPPING",
     *                                              "resellFee": 1.1,
     *                                              "shareFee": 1,
     *                                              "recommend": true
     *                                              },
     *                                               ...
     *                                          ],
     *                                          "recommend": false
     *                      },
     *                      ...
     *                  ],
     *                  "totalCount": 2,
     *                  "totalPage": 2,
     *                  "pageNo": 0,
     *                  "pageSize": 1
     *          }
     *  }
     */
    @RequestMapping(value = Routes.GIFT_PACKET_BY_PRODUCT, method = RequestMethod.GET)
    public JsonResult getGiftPacketByProduct(HttpServletRequest request, Long productId, Integer pageNo, Integer pageSize){
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            if ( pageNo == null || pageSize == null ){
                jr.remind("请输入分页条件",log);
                return;
            }
            if ( productId == null ){
                jr.remind("productId is null",log);
                return;
            }
            //查以该产品为主产品的礼包
            List<MerchantGiftPacketProduct> merchantGiftPacketProduct = merchantGiftPacketProductRepository.findByProductIdAndGiftPacketProductType(productId,GiftPacketProductType.MASTER);
            if (merchantGiftPacketProduct == null || merchantGiftPacketProduct.size() == 0){
                //如果该产品没有礼包，直接返回
                return;
            }
            List<Long> packetIdList = merchantGiftPacketProduct.stream().map(MerchantGiftPacketProduct::getPacketId).collect(Collectors.toList());
            //查礼包信息
            PageResult<MerchantGiftPacket> giftGiftPacketPage = merchantGiftPacketRepository.findByIdsPage(packetIdList,this.getPage(pageNo,pageSize));
            List<Long> giftGiftPacketPageIdList = giftGiftPacketPage.data.stream().map(MerchantGiftPacket::getId).collect(Collectors.toList());
            //查该礼包下的产品
            List<MerchantGiftPacketProduct> merchantGiftPacketProductList = merchantGiftPacketProductRepository.findByPacketIdInAndIsDelete(giftGiftPacketPageIdList, Whether.NO);
            List<Long> productIds = merchantGiftPacketProductList.stream().map(MerchantGiftPacketProduct::getProductId).collect(Collectors.toList());
            //按礼包Id分组
            Map<Long,List<MerchantGiftPacketProduct>> MerchantGiftPacketProductMap =  merchantGiftPacketProductList.stream().collect(Collectors.groupingBy(MerchantGiftPacketProduct::getPacketId));
            //查所有产品
            List<Product> productList = merchantProductRepository.findByIdInAndStatus(productIds, ProductStatus.SELLING);
            Map<Long,List<Product>> productMap =  productList.stream().collect(Collectors.groupingBy(Product::getId));

            //查礼包内的产品
            List<MerchantGiftPacketDto> merchantGiftPacketDtoList = giftGiftPacketPage.data.stream().map(giftGiftPacket->{
                MerchantGiftPacketDto merchantGiftPacketDto = new MerchantGiftPacketDto();
                RBeanUtils.copyProperties(giftGiftPacket,merchantGiftPacketDto);
                List<Product> list = new ArrayList<Product>();
                MerchantGiftPacketProductMap.get(giftGiftPacket.getId()).stream().forEach(giftPacketProduct->{
                    if (giftPacketProduct.getGiftPacketProductType() == GiftPacketProductType.MASTER){
                        list.addAll(0,productMap.get(giftPacketProduct.getProductId()));
                    }else {
                        list.addAll(productMap.get(giftPacketProduct.getProductId()));
                    }
                });
                merchantGiftPacketDto.setProductList(list);
                return merchantGiftPacketDto;
            }).collect(Collectors.toList());
            PageResult<MerchantGiftPacketDto> merchantGiftPacketDtoPage = getPage(pageNo,pageSize);
            merchantGiftPacketDtoPage.data = merchantGiftPacketDtoList;
            merchantGiftPacketDtoPage.totalPage = giftGiftPacketPage.totalPage;
            merchantGiftPacketDtoPage.totalCount = giftGiftPacketPage.totalCount;
            jr.setData(merchantGiftPacketDtoPage);
        };
        return doing.go(request, log);
    }




    /**
     * @api {put} /api/v2/customer/gift/packet/create/verify/code 创建核销码
     * @apiGroup GIFT_PACKET
     *
     * @apiHeader {String} domain <code>必须参数</code>对应平台C端域名
     * @apiHeader {String} userToken <code>必须参数</code>用户Token
     *
     * @apiParam {String} giftId 礼包id
     * @apiParam {String} mallOrderNum 平台订单id
     *
     * @apiSuccess {String} verifyCode 核销码
     * @apiSuccess {String} verifyKey 核销码
     * @apiSuccess {String} qrCodeUrl 二维码图片url 页面显示格式为:
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
     *       "code": 1,
     *       "desc": "成功"
     *       "data": {
     *          "verifyCode": "982881",
     *          "verifyKey": "982881",
     *          "qrcCodeUrl": "http://b1.dev.rockcent.com/verifyCoupon.php?CouponVerifyCode=1&MerchantId=2&VerifyCode=982881"
     *       }
     *   }
     **/
    @Transactional
    @RequestMapping(value = Routes.CUSTOMER_GIFT_PACKET_CREATE_VERIFY_CODE, method = RequestMethod.PUT)
    public JsonResult giftCreateVerifyCode(HttpServletRequest request, @RequestBody Map<String,String> dto) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {

            String giftId = dto.get("giftId");
            String mallOrderNum = dto.get("mallOrderNum");

            if (StringUtils.isBlank(giftId)) {
                jr.remind("礼包id为空",log);
                return;
            }
            if (StringUtils.isBlank(mallOrderNum)) {
                jr.remind("平台订单id为空",log);
                return;
            }

            Integer verifyCode = customerHelper.verifyCode(VerifyType.GIFT);
//            String verifyKey = customerHelper.customerCouponCodeMd5(merchantCoupon.getMerchantId(), customerDto.getId(), merchantCoupon.getId(), verifyCode);

            String verifyKey = customerHelper.customerGiftCodeMd5(giftId, customerDto.getId(), mallOrderNum, verifyCode);
            Mall mall = mallRepository.findOne(customerDto.getMallId());
            String host = mall.getCustomerClientDomain();
            if (StringUtils.isBlank(host)) {
                host = mall.getMobileHostName();
            }

            StringBuilder url = new StringBuilder();
            url.append("http://").append(host).append("/?verifyKey=").append(verifyKey).append("&giftId=").append(giftId).append("&mallOrderNum=").append(mallOrderNum);
            String qrcCodeUrl = qrCodeHelper.createBase64QRCode(url.toString());
            CustomerGiftWallet customerGiftWallet = new CustomerGiftWallet();
            customerGiftWallet.setVerifyCode(String.valueOf(verifyCode));
            customerGiftWallet.setVerifyKey(verifyKey);
            customerGiftWallet = customerGiftWalletRepository.save(customerGiftWallet);
            customerGiftWallet.setQrcCodeUrl(qrcCodeUrl);
            jr.data = customerGiftWallet;
        };
        return doing.go(request, log);
    }


    /**
     * @api {put} /api/v2/customer/gift/packet/to/verify/list 礼包待核销产品和卡券列表
     * @apiGroup GIFT_PACKET
     *
     * @apiHeader {String} domain <code>必须参数</code>对应平台C端域名
     * @apiHeader {String} userToken <code>必须参数</code>用户Token
     *
     * @apiParam {String} verifyCode verifyCode
     * @apiParam {String} verifyKey verifyKey
     * @apiParam {String} giftId 礼包id
     * @apiParam {String} mallOrderNum 平台订单id
     * @apiParam {Long} verifyCustomerId <code>必传参数</code> 核销员ID
     *
     *
     * @apiSuccess {String} id 产品或者卡券id
     * @apiSuccess {String} name 产品或者卡d
     * @apiSuccess {String} type 类型，PRODUCT：产品;COUPON:卡券
     * @apiSuccess {String} merchantOrderNum 商户订单号
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
     *       "code": 1,
     *       "desc": "成功"
     *       "data": [{
     *          "id": "100",
     *          "name": "冰红茶",
     *          "count": 3,
     *          "merchantOrderNum": "05131504849316094_3",
     *          "type":"PRODUCT"
     *       },
     *       {
     *          "id": "101",
     *          "name": "冰红茶",
     *          "merchantOrderNum": "05131504849316094_3",
     *          "type":"COUPON"
     *       }
     *
     *       ]
     *   }
     **/
    @Transactional
    @RequestMapping(value = Routes.CUSTOMER_GIFT_PACKET_TO_VERIFY_LIST, method = RequestMethod.GET)
    public JsonResult toVerifyProductOrCouponList(HttpServletRequest request, GiftVerifyDto verifyDto) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {

            String verifyCode = verifyDto.getVerifyCode();
            String verifyKey = verifyDto.getVerifyKey();
            Long giftId = verifyDto.getGiftId();
            String mallOrderNum = verifyDto.getMallOrderNum();
            Long verifyId = verifyDto.getVerifyCustomerId();

            if (null == giftId) {
                jr.remind("礼包id为空", log);
                return;
            }
            if (null == verifyId) {
                jr.remind("核销人员", log);
                return;
            }
//            if (StringUtils.isBlank(mallOrderNum)) {
//                jr.remind("平台订单id为空",log);
//                return;
//            }


            List<GiftVerifyItemDto> productItems = mallOrderRepository.findProductItemsByVerifyPersonId(verifyDto);
            List<GiftVerifyItemDto> couponItems = customerCouponWalletRepository.findCustomerCouponByVerifyPersonId(customerDto.getId(),verifyId);
            List<GiftVerifyItemDto> totals = new ArrayList<>();
            productItems.addAll(productItems);
            productItems.addAll(couponItems);
            jr.data= totals;
        };
        return doing.go(request, log);
    }

}
